package com.tl.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.tl.domain.Ball;

public class UpdateDataTask extends TimerTask {

	Logger logger = Logger.getLogger(UpdateDataTask.class);
	
	public static void main(String[] args) {
		new Timer().schedule(new UpdateDataTask(), 0);
	}
	
	@Override
	public void run() {
		List<Ball> balls = getNetNewData();
		ImportData.importDB(balls);
	}
	
	/**
	 * 获取网络上最新数据
	 * @return
	 */
	public List<Ball> getNetNewData(){
		Calendar c = Calendar.getInstance();
		int curYear = c.get(Calendar.YEAR);
		String URL = "http://hao123.lecai.com/lottery/draw/list/50?d="+curYear+"-01-01";
		List<Ball> balls = new ArrayList<Ball>();
		ImportData.getAnalysisHTML(URL, curYear+"", balls);
		Collections.sort(balls,new Comparator<Ball>() {
			@Override
			public int compare(Ball o1, Ball o2) {
				return o1.getTime().compareTo(o2.getTime());
			}
		});
		List<Ball> tempBalls = new ArrayList<Ball>();
		String sql = "select max(issue) issue,batch from lottery where year="+curYear+"";
		Hashtable<String, Object> query = JDBCUtils.getQuerySingle(sql);
		String maxTime = String.valueOf(query.get("issue"));
		Integer batch = Integer.parseInt(query.get("batch").toString());
		SimpleDateFormat dateFor = new SimpleDateFormat("yyyy-MM-dd");
		for(Ball b: balls){
			String time = b.getTime();
			try {
				if(dateFor.parse(time).getTime()>dateFor.parse(maxTime).getTime()){
					batch +=1;
					b.setBatch(batch);
					tempBalls.add(b);
				}
			} catch (ParseException e) {
				e.printStackTrace();
				return null;
			}
		}
		return tempBalls;
	}
}
